
package com.springmvc.netty.server;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.springmvc.netty.client.NettyClients;

public class GameEventHandler {

	protected SocketIOServer server;

	@Autowired
	public GameEventHandler(SocketIOServer server) {
		this.server = server;
	}

	@OnConnect
	public void onConnect(SocketIOClient client) {
		UserClient beiMiClient = NettyClients.getInstance().getClient(client.getSessionId().toString());
		if (beiMiClient != null && !StringUtils.isBlank(beiMiClient.getUserid())) {
			client.sendEvent("chatevent", beiMiClient.getUserid());
		}
	}

	//添加@OnDisconnect事件，客户端断开连接时调用，刷新客户端信息  
	@OnDisconnect
	public void onDisconnect(SocketIOClient client) {
		UserClient beiMiClient = NettyClients.getInstance().getClient(client.getSessionId().toString());
		if (beiMiClient != null) {
			System.out.println(beiMiClient.getUserid());
			client.sendEvent("chatevent", beiMiClient.getUserid());
		}
	}

	//抢地主事件
	@OnEvent(value = "chatevent")
	public void onJoinRoom(SocketIOClient client, AckRequest request, String data) {
		UserClient beiMiClient = JSON.parseObject(data, UserClient.class);
		beiMiClient.setClient(client);
		beiMiClient.setUserid("123456");
		beiMiClient.setSession(client.getSessionId().toString());
		/**
		 * 心跳时间
		 */
		beiMiClient.setTime(System.currentTimeMillis());
		NettyClients.getInstance().putClient("123456", beiMiClient);

	}

}